# -*- coding: utf-8 -*-
# created on 2016/11/30
#

from sympy import I
from sympy.abc import z, Z
from mathsolver.functions.base import *
from mathsolver.functions.base.base import new_latex


def fs_default_symbol(expr, args=None):
    if args is None:
        args = []
    if len(args) > 1:
        return args[1].sympify()
    elif z in expr.free_symbols:
        return z
    elif Z in expr.free_symbols:
        return Z
    else:
        return expr.free_symbols.pop()


class Complex(object):  # 复数
    def __init__(self, poly, sym="i"):
        poly = str(poly)
        self.comPoly = poly.replace(sym, "I")
        self.sym = sym  # 虚部符号
        self.normPoly = self.normalized()
        self.real, self.imag = self.real_imag()
        self.length = self.length()
        self.conjugate = self.conjugate()

    def normalized(self):
        poly = self.comPoly
        poly = sympify(poly)
        poly = poly.simplify()
        poly = poly.expand()
        return poly

    def real_imag(self):
        poly = self.normPoly
        if str(poly).find(str('I')) >= 0:
            real, imag = poly.as_independent(I, as_Add=True)
            imag = imag.coeff("I")
        else:
            real = poly
            imag = S.Zero
        return real, imag

    def length(self):  # 模长
        value = sqrt(self.real ** 2 + self.imag ** 2)
        value = value.expand().simplify()
        return value

    def conjugate(self):  # 共轭复数
        value = self.real - self.imag * I
        return value

    def normalized_eq(self):  # 复数的标准式
        return BaseValue(self.real + self.imag * I)

    def _printing(self):
        poly = self.normPoly
        poly = new_latex(poly)
        poly = poly.replace(str('I'), str('i'))
        return poly

    @staticmethod
    def print_complex(poly):  # poly是一个Sympy表达式
        return Complex(poly)._printing()

    @staticmethod
    def instance(a, b):
        return Complex(a + b * I)


if __name__ == '__main__':
    pass
